<template>
  <el-select
    :style="style"
    :allowClear="clearable"
    v-bind="$attrs"
    :value="value"
    :placeholder="placeholder"
    @change="change"
  >
    <el-option
      v-for="option in list"
      :key="option[props.code]"
      :value="option[props.code]"
      :label="option[props.name]"
    >
    </el-option>
  </el-select>
</template>
<script>
import { queryByFjbm } from "@/api/checkTask/task";
export default {
  name: "DictionarySelect",
  inheritAttrs: false,
  model: {
    prop: "value",
    event: "change",
  },
  props: {
    placeholder: {
      type: String,
      default: "请选择",
    },
    clearable: {
      type: Boolean,
      default: true,
    },
    treeData: {
      type: Array,
      default: null,
    },
    source: {
      type: String,
      default: "",
    },
    value: {
      type: String,
    },
    width: {
      default: "100%",
      type: [Number, String],
    },
    onChange: {
      type: Function,
    },
    props: {
      type: Object,
      default: function () {
        return {
          name: "mc",
          code: "bm",
        };
      },
    },
  },
  computed: {
    style: function () {
      if (typeof this.width === "string") {
        return { width: this.width };
      }
      if (typeof this.width === "number") {
        return { width: this.width + "px" };
      }
    },
  },
  data() {
    return {
      list: [],
    };
  },
  created() {
    if (this.treeData === null) {
      this.getData(this.source);
    } else {
      this.list = this.treeData;
    }
  },
  watch: {
    source: function (source) {
      this.getData(source);
    },
  },
  methods: {
    change(v) {
      this.$emit("change", v);
      this.onChange?.(v);

      let item = null;
      this.list.forEach((el) => {
        if (el.bm == v) {
          item = el;
        }
      });
      this.$emit("getJWDXX", item);
    },
    getData(source) {
      queryByFjbm(source).then((response) => {
        this.list = response.data;
      });
    },
  },
};
</script>
